package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.config.constant.MqConst;
import com.atguigu.gmall.common.config.service.RabbitService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author atguigu-mqx
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    //  调用服务层！
    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;


    @GetMapping("/findAll")
    public Result findAll(){
        //  获取到所有要秒杀的商品列表！都在缓存中存储！ seckill:goods
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        return Result.ok(seckillGoodsList);
    }

    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){
        //  获取数据 hget key field
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  加密：有个前提： 必须在秒杀时间范围内存生产！
        //  获取到秒杀商品
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        if (seckillGoods!=null && !StringUtils.isEmpty(userId)){
            //  在秒杀的时间范围内
            Date currentTime = new Date();
            //  当前系统时间在开始时间之后，结束时间之前！
            if (DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime)
                && DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //  生成下单码
                String skuIdStr = DigestUtils.md5DigestAsHex(userId.getBytes());
                //  String encrypt = MD5.encrypt(userId);
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("生成下单码失败!");
    }

    //  下单： /api/activity/seckill/auth/seckillOrder/{skuId}?skuIdStr=xxx
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request ){
        // 业务逻辑 校验下单码：
        String skuIdStr = request.getParameter("skuIdStr");
        //  后台生成下单码：
        String userId = AuthContextHolder.getUserId(request);

        if (!skuIdStr.equals(DigestUtils.md5DigestAsHex(userId.getBytes()))){
            //  信息提示
            //  return Result.fail().message("校验下单码失败!");
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        //  校验状态位state 本质：在Map 中，key = skuId value = 0 | 1
        String state = (String) CacheHelper.get(skuId.toString());
        if (StringUtils.isEmpty(state)){
            //  信息提示
            // return Result.fail().message("获取状态位失败!");
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }else if ("0".equals(state)){
            //  信息提示
            //            return Result.fail().message("商品已经售罄");
           return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }else {
            //  可以秒杀，我们将用户信息，与秒杀商品信息放入mq 中，进行排队处理！
            //  发送的消息与监听消息有关系！ userId ,skuId
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);
            //  表示将用户信息与秒杀商品信息存储到队列中！
            this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,MqConst.ROUTING_SECKILL_USER,userRecode);
        }
        //  返回默认200
        return Result.ok();
    }

    //  检查订单状态： 页面每隔3秒钟触发一次！
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  获取到用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法
        return seckillGoodsService.checkOrder(skuId, userId);
    }

    //  下订单页面控制器
    @GetMapping("auth/trade")
    public Result tradeOrder(HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);

        //  userAddressList detailArrayList totalNum totalAmount
        HashMap<String, Object> map = new HashMap<>();
        //  获取map 中对应的value 数据。
        //  获取用户收货地址列表！
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        //  获取到订单明细！ 存储的是秒杀的商品！
        //  hget key field
        OrderRecode orderRecode = (OrderRecode) this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);
        //  判断
        if(orderRecode==null){
            return Result.fail().message("非法操作");
        }
        //  通过orderRecode 获取到秒杀的商品是谁！ 一个人只能秒一个商品！ 秒杀完成之后，才可以秒杀另外的商品！
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
        List<OrderDetail> detailArrayList = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        //  赋值！
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        //  将在这个订单明细存储到集合中
        detailArrayList.add(orderDetail);
        //  在map 中存储对应的key
        map.put("userAddressList",userAddressList);
        map.put("detailArrayList",detailArrayList);
        map.put("totalNum",1);
        //  如果秒杀可以购买多个商品，则计算商品的总金额应该如何处理？
//        OrderInfo orderInfo = new OrderInfo();
//        orderInfo.setOrderDetailList(detailArrayList);
//        orderInfo.sumTotalAmount();
//        map.put("totalAmount",orderInfo.getTotalAmount());
        map.put("totalAmount",orderDetail.getOrderPrice());

        //  返回map 集合数据！
        return Result.ok(map);
    }

    //  编写下订单的控制器：
    @PostMapping("/auth/submitOrder")
    public Result authSubmitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  细节： 这个位置，将用户Id 赋值给orderInfo 对象，为什么不在orderApiController 中获取！ 请求地址是service-activity,并非order!
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //  远程调用保存订单！
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        //  判断
        if(orderId==null){
            return Result.fail().message("下单失败，请重新操作");
        }
        //  细节：删除 RedisConst.SECKILL_ORDERS 预下单记录！
        this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);

        //  保存：真正的下单记录！
        //  hset key = RedisConst.SECKILL_ORDERS_USERS field = userId  value = orderId
        this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId,orderId.toString());
        //  返回数据
        return Result.ok(orderId);
    }

}
